package com.test.springboot.springboot3testdemo3.config;

import com.google.common.util.concurrent.ThreadFactoryBuilder;
import java.util.Objects;
import java.util.concurrent.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

/**
 * Created with IntelliJ IDEA.
 *
 * @author： liuziyang
 * @date： 2024/9/12-15:02
 * @description：
 * @modifiedBy：
 * @version: 1.0
 */
@Configuration
public class ThreadPoolConfig {

  @Bean(name = "threadPoolExecutor")
  public ThreadPoolExecutor executorService() {
    // 1.创建一个自己定义的线程池
    ThreadPoolExecutor executorService =
        new ThreadPoolExecutor(
            2,
            3,
            0,
            TimeUnit.MILLISECONDS,
            new LinkedBlockingQueue(10),
            new ThreadFactoryBuilder().setNameFormat("test-pool-%d").setDaemon(true).build()) {
          private static final Logger LOGGER = LoggerFactory.getLogger("test-pool");

          // 重写afterExecute方法
          @Override
          protected void afterExecute(Runnable r, Throwable t) {
            // 这个是excute提交的时候
            if (t != null) {
              LOGGER.warn("afterExecute里面获取到excute提交的异常信息，处理异常{}", t.getMessage());
            }
            // 如果r的实际类型是FutureTask 那么是submit提交的，所以可以在里面get到异常
            if (r instanceof FutureTask) {
              try {
                Future<?> future = (Future<?>) r;
                // get获取异常
                future.get();

              } catch (Exception e) {
                LOGGER.warn("afterExecute里面获取到submit提交的异常信息，处理异常", e);
              }
            }
          }
        };

    return executorService;
  }

  @Bean()
  public Executor threadPoolExecutor() {
    ThreadPoolTaskExecutor threadPoolExecutor =
        new ThreadPoolTaskExecutor() {
          /**
           * @param task
           * @param ex
           */
          @Override
          protected void afterExecute(Runnable task, Throwable ex) {
            // 这个是excute提交的时候
            if (Objects.nonNull(ex)) {
              logger.warn("afterExecute里面获取到excute提交的异常信息，处理异常", ex);
            }
            // 如果r的实际类型是FutureTask 那么是submit提交的，所以可以在里面get到异常
            if (task instanceof FutureTask future) {
              try {
                // get获取异常
                future.get();

              } catch (Exception e) {
                logger.warn("afterExecute里面获取到submit提交的异常信息，处理异常", e);
              }
            }
            super.afterExecute(task, ex);
          }
        };
    // 返回可用处理器的Java虚拟机的数量
    int processNum = Runtime.getRuntime().availableProcessors();
    int corePoolSize = (int) (processNum / (1 - 0.2));
    int maxPoolSize = (int) (processNum / (1 - 0.5));
    // 核心池大小
    threadPoolExecutor.setCorePoolSize(corePoolSize);
    // 最大线程数
    threadPoolExecutor.setMaxPoolSize(maxPoolSize);
    // 队列程度
    threadPoolExecutor.setQueueCapacity(maxPoolSize * 1000);
    threadPoolExecutor.setThreadPriority(Thread.MAX_PRIORITY);
    threadPoolExecutor.setDaemon(false);
    // 线程空闲时间
    threadPoolExecutor.setKeepAliveSeconds(300);
    // 线程名字前缀
    threadPoolExecutor.setThreadNamePrefix("test-Executor-");
    return threadPoolExecutor;
  }
}
